package leetcode;

public class jieyushui2 {
    public static int trap(int[] nums) {
        if(nums.length==0||nums==null){
            return -1;
        }
        int n=nums.length;
        int[] leftMax=new int[n];
        int[] rightMax=new int[n];
        int water=0;
        int m=0;
        int p=0;
        //从左到右求
        leftMax[0]=0;
        for(int i=1;i<n;i++){
            leftMax[i]=Math.max(leftMax[i-1],nums[i-1]);
        }
        //从右往左求
        rightMax[n-1]=0;
        for(int i=n-2;i>=0;i--){
            rightMax[i]=Math.max(rightMax[i+1],nums[i+1]);
        }
        for(int i=1;i<n-1;i++){
            m=Math.min(rightMax[i],leftMax[i]);
            p=m-nums[i];
            if(p>0){
                water=water+p;
            }else{
                water=water;
            }
        }
        if(nums.length==2||nums.length==1){
            return  water;
        }
        return water;


    }

    public static void main(String[] args) {
        int[]  array={2,1,4,0,2,1,5,2,3,0,1};
        int trap = trap(array);
        System.out.println(trap);
    }
}
